import { z } from 'zod'
import { procedure, router } from '../trpc'

export const toolsRouter = router({
  // JSON 格式化
  formatJson: procedure
    .input(z.object({
      json: z.string(),
      indent: z.number().min(0).max(8).default(2)
    }))
    .mutation(({ input }) => {
      try {
        const parsed = JSON.parse(input.json)
        const formatted = JSON.stringify(parsed, null, input.indent)
        return {
          success: true,
          formatted,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          formatted: null,
          error: error instanceof Error ? error.message : 'Invalid JSON'
        }
      }
    }),

  // Base64 编码
  encodeBase64: procedure
    .input(z.object({
      text: z.string()
    }))
    .mutation(({ input }) => {
      try {
        const encoded = Buffer.from(input.text, 'utf-8').toString('base64')
        return {
          success: true,
          result: encoded,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          error: error instanceof Error ? error.message : 'Encoding failed'
        }
      }
    }),

  // Base64 解码
  decodeBase64: procedure
    .input(z.object({
      base64: z.string()
    }))
    .mutation(({ input }) => {
      try {
        const decoded = Buffer.from(input.base64, 'base64').toString('utf-8')
        return {
          success: true,
          result: decoded,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          error: error instanceof Error ? error.message : 'Invalid Base64'
        }
      }
    }),

  // UUID 生成
  generateUuid: procedure
    .input(z.object({
      version: z.enum(['v1', 'v4']).default('v4'),
      count: z.number().min(1).max(100).default(1)
    }))
    .mutation(({ input }) => {
      try {
        const { randomUUID } = require('crypto')
        const uuids: string[] = []
        
        for (let i = 0; i < input.count; i++) {
          if (input.version === 'v4') {
            uuids.push(randomUUID())
          } else {
            // 简化的 v1 UUID 生成（实际项目中应使用专门的库）
            uuids.push(randomUUID())
          }
        }
        
        return {
          success: true,
          uuids,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          uuids: [],
          error: error instanceof Error ? error.message : 'UUID generation failed'
        }
      }
    }),

  // 正则表达式测试
  testRegex: procedure
    .input(z.object({
      pattern: z.string(),
      flags: z.string().optional(),
      testString: z.string()
    }))
    .mutation(({ input }) => {
      try {
        const regex = new RegExp(input.pattern, input.flags || '')
        const matches = input.testString.match(regex)
        const globalMatches = input.testString.matchAll(new RegExp(input.pattern, (input.flags || '') + 'g'))
        const allMatches = Array.from(globalMatches)
        
        return {
          success: true,
          isMatch: regex.test(input.testString),
          matches: matches || [],
          allMatches: allMatches.map(match => ({
            match: match[0],
            index: match.index || 0,
            groups: match.slice(1)
          })),
          error: null
        }
      } catch (error) {
        return {
          success: false,
          isMatch: false,
          matches: [],
          allMatches: [],
          error: error instanceof Error ? error.message : 'Invalid regex pattern'
        }
      }
    }),

  // URL 编码
  encodeUrl: procedure
    .input(z.object({
      text: z.string(),
      type: z.enum(['component', 'full']).default('component')
    }))
    .mutation(({ input }) => {
      try {
        let encoded: string
        if (input.type === 'component') {
          encoded = encodeURIComponent(input.text)
        } else {
          encoded = encodeURI(input.text)
        }
        
        return {
          success: true,
          result: encoded,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          error: error instanceof Error ? error.message : 'URL encoding failed'
        }
      }
    }),

  // URL 解码
  decodeUrl: procedure
    .input(z.object({
      text: z.string(),
      type: z.enum(['component', 'full']).default('component')
    }))
    .mutation(({ input }) => {
      try {
        let decoded: string
        if (input.type === 'component') {
          decoded = decodeURIComponent(input.text)
        } else {
          decoded = decodeURI(input.text)
        }
        
        return {
          success: true,
          result: decoded,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          error: error instanceof Error ? error.message : 'URL decoding failed'
        }
      }
    }),

  // 颜色转换
  convertColor: procedure
    .input(z.object({
      color: z.string(),
      fromFormat: z.enum(['hex', 'rgb', 'hsl', 'hsv']),
      toFormat: z.enum(['hex', 'rgb', 'hsl', 'hsv'])
    }))
    .mutation(({ input }) => {
      try {
        // 辅助函数：解析十六进制颜色
        const parseHex = (hex: string) => {
          const clean = hex.replace('#', '')
          if (clean.length === 3) {
            const r = parseInt(clean[0] + clean[0], 16)
            const g = parseInt(clean[1] + clean[1], 16)
            const b = parseInt(clean[2] + clean[2], 16)
            return { r, g, b }
          } else if (clean.length === 6) {
            const r = parseInt(clean.substr(0, 2), 16)
            const g = parseInt(clean.substr(2, 2), 16)
            const b = parseInt(clean.substr(4, 2), 16)
            return { r, g, b }
          }
          throw new Error('Invalid hex format')
        }

        // 辅助函数：解析RGB颜色
        const parseRgb = (rgb: string) => {
          const match = rgb.match(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/)
          if (!match) throw new Error('Invalid RGB format')
          return {
            r: parseInt(match[1]),
            g: parseInt(match[2]),
            b: parseInt(match[3])
          }
        }

        // 辅助函数：RGB转HSL
        const rgbToHsl = (r: number, g: number, b: number) => {
          r /= 255
          g /= 255
          b /= 255
          const max = Math.max(r, g, b)
          const min = Math.min(r, g, b)
          let h = 0, s = 0, l = (max + min) / 2

          if (max !== min) {
            const d = max - min
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
            switch (max) {
              case r: h = (g - b) / d + (g < b ? 6 : 0); break
              case g: h = (b - r) / d + 2; break
              case b: h = (r - g) / d + 4; break
            }
            h /= 6
          }

          return {
            h: Math.round(h * 360),
            s: Math.round(s * 100),
            l: Math.round(l * 100)
          }
        }

        // 辅助函数：HSL转RGB
        const hslToRgb = (h: number, s: number, l: number) => {
          h /= 360
          s /= 100
          l /= 100

          const hue2rgb = (p: number, q: number, t: number) => {
            if (t < 0) t += 1
            if (t > 1) t -= 1
            if (t < 1/6) return p + (q - p) * 6 * t
            if (t < 1/2) return q
            if (t < 2/3) return p + (q - p) * (2/3 - t) * 6
            return p
          }

          let r, g, b
          if (s === 0) {
            r = g = b = l
          } else {
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s
            const p = 2 * l - q
            r = hue2rgb(p, q, h + 1/3)
            g = hue2rgb(p, q, h)
            b = hue2rgb(p, q, h - 1/3)
          }

          return {
            r: Math.round(r * 255),
            g: Math.round(g * 255),
            b: Math.round(b * 255)
          }
        }

        // 解析输入颜色
        let rgb: { r: number, g: number, b: number }
        
        if (input.fromFormat === 'hex') {
          rgb = parseHex(input.color)
        } else if (input.fromFormat === 'rgb') {
          rgb = parseRgb(input.color)
        } else if (input.fromFormat === 'hsl') {
          const match = input.color.match(/hsl\s*\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/)
          if (!match) throw new Error('Invalid HSL format')
          const h = parseInt(match[1])
          const s = parseInt(match[2])
          const l = parseInt(match[3])
          rgb = hslToRgb(h, s, l)
        } else {
          throw new Error('HSV format not supported yet')
        }

        // 转换为目标格式
        let result: string
        
        if (input.toFormat === 'hex') {
          const toHex = (n: number) => n.toString(16).padStart(2, '0')
          result = `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
        } else if (input.toFormat === 'rgb') {
          result = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`
        } else if (input.toFormat === 'hsl') {
          const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
          result = `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`
        } else {
          throw new Error('HSV format not supported yet')
        }

        return {
          success: true,
          result,
          rgb,
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          rgb: null,
          error: error instanceof Error ? error.message : 'Color conversion failed'
        }
      }
    }),

  // 时间戳转换
  convertTimestamp: procedure
    .input(z.object({
      input: z.string(),
      fromFormat: z.enum(['timestamp', 'datetime']),
      toFormat: z.enum(['timestamp', 'datetime', 'iso', 'relative'])
    }))
    .mutation(({ input }) => {
      try {
        let date: Date
        
        if (input.fromFormat === 'timestamp') {
          const timestamp = parseInt(input.input)
          if (isNaN(timestamp)) {
            throw new Error('Invalid timestamp format')
          }
          // 判断是秒还是毫秒时间戳
          const timestampMs = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
          date = new Date(timestampMs)
        } else {
          // datetime format
          date = new Date(input.input)
        }
        
        if (isNaN(date.getTime())) {
          throw new Error('Invalid date')
        }
        
        let result: string
        
        switch (input.toFormat) {
          case 'timestamp':
            result = Math.floor(date.getTime() / 1000).toString()
            break
          case 'datetime':
            result = date.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            })
            break
          case 'iso':
            result = date.toISOString()
            break
          case 'relative':
            const now = new Date()
            const diff = now.getTime() - date.getTime()
            const seconds = Math.floor(diff / 1000)
            const minutes = Math.floor(seconds / 60)
            const hours = Math.floor(minutes / 60)
            const days = Math.floor(hours / 24)
            
            if (days > 0) {
              result = `${days}天前`
            } else if (hours > 0) {
              result = `${hours}小时前`
            } else if (minutes > 0) {
              result = `${minutes}分钟前`
            } else if (seconds > 0) {
              result = `${seconds}秒前`
            } else {
              result = '刚刚'
            }
            break
          default:
            throw new Error('Unsupported format')
        }
        
        return {
          success: true,
          result,
          timestamp: Math.floor(date.getTime() / 1000),
          timestampMs: date.getTime(),
          datetime: date.toLocaleString('zh-CN'),
          iso: date.toISOString(),
          error: null
        }
      } catch (error) {
        return {
          success: false,
          result: null,
          timestamp: null,
          timestampMs: null,
          datetime: null,
          iso: null,
          error: error instanceof Error ? error.message : 'Timestamp conversion failed'
        }
      }
    }),
})